import 'package:flutter_baselib/flutter_baselib.dart';
import 'package:flutter_baselib/src/config/bugly_config.dart';
import 'package:flutter_bugly_plugin/lib.dart';
import 'package:flutter_xlog_plugin/xlog_lib.dart';

import 'config/log_config.dart';

///@date:  2021/2/23 13:52
///@author:  lixu
///@description: 基础库
class BaseLibPlugin {
  BaseLibPlugin._();

  ///是否是debug模式
  static bool _isDebug = true;

  ///全局资源配置类
  static late IResConfig _resConfig;

  static bool get isDebug => _isDebug;

  static IResConfig get resConfig => _resConfig;

  ///初始化基础库,应用启动时调用
  ///[isDebug] 是否是debug模式
  ///[logConfig] 日志库配置
  ///[httpConfig] http相关配置信息
  ///[resConfig] 全局通用资源配置
  ///[buglyConfig] bugly相关配置信息，为null不使用bugly
  ///[toastImpl] Toast相关配置，为null使用默认Toast样式
  static Future<void> init({
    required bool isDebug,
    required LogConfig logConfig,
    required IHttpConfig httpConfig,
    required IResConfig resConfig,
    BuglyConfig? buglyConfig,
    IToast? toastImpl,
  }) async {
    _isDebug = isDebug;
    _resConfig = resConfig;

    Constants.initPageIndex = _resConfig.configInitPageIndex();
    Constants.pageSize = _resConfig.configPageSize();

    ///初始化bugly
    if (buglyConfig != null) {
      await FlutterBugly.init(
        androidAppId: buglyConfig.androidAppId,
        iOSAppId: buglyConfig.iOSAppId,
        channel: buglyConfig.channel,
        autoCheckUpgrade: buglyConfig.autoCheckUpgrade,
        autoInit: buglyConfig.autoInit,
        autoDownloadOnWifi: buglyConfig.autoDownloadOnWifi,
        enableHotfix: buglyConfig.enableHotfix,
        enableNotification: buglyConfig.enableNotification,
        showInterruptedStrategy: buglyConfig.showInterruptedStrategy,
        canShowApkInfo: buglyConfig.canShowApkInfo,
        initDelay: buglyConfig.initDelay,
        upgradeCheckPeriod: buglyConfig.upgradeCheckPeriod,
        checkUpgradeCount: buglyConfig.checkUpgradeCount,
        customUpgrade: buglyConfig.customUpgrade,
      );
    }

    ///初始化日志库
    await XLogUtils.init(
      tag: logConfig.tag,
      isConsolePrintLog: logConfig.isConsolePrintLog,
      isUseFlutterPrintMethodLog: logConfig.isFlutterPrintLog,
      saveLogFilePath: logConfig.saveLogFilePath,
      encryptPubKey: logConfig.encryptPubKey,
    );

    ///初始化Toast
    ToastUtils.init(toastImpl);

    ///初始化http组件
    XApi.init(httpConfig);
  }

  ///应用关闭时调用该方法
  static Future<void> dispose() async {
    await XLogUtils.dispose();
    FlutterBugly.dispose();
  }
}
